package com.controller;

import com.controller.vo.ResultVO;
import com.dto.PostDTO;
import com.entity.Post;
import com.entity.PostComment;
import com.exception.GlobalException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.PostCommentService;
import com.service.PostService;
import com.service.TaskMonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import static com.utils.CreateUserDir.generateUserDirName;

/**
 * ClassName: PostController
 * Description:
 *
 * @author L_Z_R
 * @version 1.0
 * @create 2025/05/19 15:00
 */
@RestController
public class PostController extends BaseController {
    @Autowired
    private PostService postService;

    @Autowired
    private PostCommentService postCommentService;

    @Autowired
    private TaskMonitorService taskMonitorService;

    /**
     * 发布帖子
     *
     * @param postDTOJson  帖子信息的复合对象
     * @param files    帖子媒体文件数组
     * @param username 发帖人的名字
     * @return String
     *
     * Jackson 默认不支持对 Java 8 的 java.time.LocalDateTime 类型进行反序列化操作
     * 需要添加 jackson-datatype-jsr310 模块，并且在 ObjectMapper 里注册该模块
     */
    @PostMapping(path = "/addPost", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultVO<String> addPost(@RequestPart("postDTO") String postDTOJson,
                                    @RequestPart(value = "files", required = false) MultipartFile[] files,
                                    @RequestPart("username") String username
    ) throws IOException {

        // 创建 ObjectMapper 并注册 JavaTimeModule
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());

        // 将 JSON 字符串转换为 PostDTO 对象
        PostDTO postDTO = objectMapper.readValue(postDTOJson, PostDTO.class);

        //1. 设置帖子媒体的存储路径
        String baseDir = "D:\\project\\fish\\upload\\postmedia\\";
        Path basePath = Paths.get(baseDir);

        //2. 生成用户专属文件夹
        String userDirName = generateUserDirName(basePath, username);
        Path userDir = basePath.resolve(userDirName);

        //3. 判断用户文件夹是否存在,不存在则创建
        if (!Files.exists(userDir)) {
            Files.createDirectories(userDir);
        }

        //4. 保存所有文件到该目录下
        List<String> addFiles = new ArrayList<>();
        if (files != null) {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    String fileName = file.getOriginalFilename();
                    assert fileName != null;
                    Path filePath = userDir.resolve(fileName);
                    file.transferTo(filePath);
                    addFiles.add(filePath.toString());
                }
            }
        }

        //5. 将路径添加进 PostMedia 对象中
        if (!addFiles.isEmpty()) {
            String joinedPaths = String.join(",", addFiles);
            postDTO.getPostMedia().setUrl(joinedPaths);//将写入的文件的路径传入实体类
        }
        //6. 添加帖子信息
        postService.addPost(postDTO);

        //监控发帖任务
        taskMonitorService.checkAndRewardTask(postDTO.getPost().getAccountId(), (byte) 2);
        return success("发布成功");
    }


    //获取所有的帖子信息
    @GetMapping("/getAllPost")
    public ResultVO<List<Post>> getAllPost(@RequestParam(required = false) Integer currentUserId) {
        List<Post> posts = postService.getAllPostsWithDetails(currentUserId);
        System.out.println(posts);
        return success(posts);
    }

    // 根据板块id查询对应板块下的所有帖子
    @GetMapping("/getPostsByPlateId")
    public ResultVO<List<Post>> getPostsByPlateId(@RequestParam("plateId") Integer plateId,
                                                  @RequestParam(required = false) Integer currentUserId) {
        List<Post> posts = postService.getPostsByPlateId(plateId, currentUserId);
        return success(posts);
    }

    //根据帖子id查询帖子信息
    @GetMapping("/getPostsByPostId")
    public ResultVO<List<Post>> getPostsByPostId(@RequestParam("postId") Integer postId,
                                                 @RequestParam(required = false) Integer currentUserId) {
        List<Post> posts = postService.getPostsByPostId(postId, currentUserId);
              return success(posts);
    }

    //获取所有的热门帖子信息
    @GetMapping("/hotPost")
    public ResultVO<List<Post>> getHotPosts(@RequestParam(required = false) Integer currentUserId) {
        List<Post> posts = postService.getHotPostsWithDetails(currentUserId);
        return success(posts);
    }

    //保存帖子评论
    @PostMapping("/savePostComment")
    public ResultVO<String> savePostComment(@RequestBody PostComment postComment) {
        postCommentService.addComment(postComment);
        //监控评论任务
        taskMonitorService.checkAndRewardTask(postComment.getAccountId(), (byte) 3);
        return success("添加评论成功");
    }

    //查询未审核的帖子信息
    @GetMapping("/getAllAuditPost")
    public ResultVO<PageInfo<Post>> getAllAuditPost(@RequestParam(defaultValue = "1") int pageNum,
                                                    @RequestParam(defaultValue = "10") int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Post> allPost = postService.getAllAuditPost(pageNum, pageSize);
        return success(allPost);
    }

    //审核帖子
    @PostMapping("/auditPost")
    public ResultVO<String> auditPost(@RequestParam Integer postId, @RequestParam Integer auditStatus) {
        postService.auditPost(postId, auditStatus);
        return success();
    }

    //获取用户发布的帖子信息
    @GetMapping("/getAllPostByAccountId")
    public ResultVO<List<Post>> getAllPostByAccountId(@RequestParam Integer accountId) {
        List<Post> allPost = postService.getAllAuditPostByAccountId(accountId);
        return success(allPost);
    }

    @PostMapping("/stickPost")
    public ResultVO<String> stickPost(@RequestParam Integer postId,@RequestParam Integer accountId) {
        if (accountId != 4){
            throw new GlobalException(1001, "该用户权限不足");
        }
        postService.stickPost(postId);
        return success();
    }
    @PostMapping("/essencePost")
    public ResultVO<String> essencePost(@RequestParam Integer postId,@RequestParam Integer accountId) {
        if (accountId != 4){
            throw new GlobalException(1001, "该用户权限不足");
        }
        postService.essencePost(postId);
        return success();
    }

}
